// 在线分析页面的JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 模拟数据刷新功能
    const refreshBtn = document.querySelector('.refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            this.classList.add('rotating');
            setTimeout(() => {
                this.classList.remove('rotating');
                updateStreamData();
            }, 1000);
        });
    }

    // 初始化下拉菜单
    initDropdowns();

    // 初始化参数选择器
    initParameterSelector();

    // 初始化时间范围选择器
    initTimeSelector();

    // 初始化过滤器按钮
    initFilterButtons();

    // 初始化图表
    initCharts();

    // 初始化模拟实时数据更新
    startRealTimeUpdates();
});

// 模拟更新流数据
function updateStreamData() {
    const streamItems = document.querySelectorAll('.stream-item');
    
    streamItems.forEach(item => {
        const valueElement = item.querySelector('.stream-value');
        const trendElement = item.querySelector('.stream-trend');
        const statusElement = item.querySelector('.stream-status');
        
        // 获取当前值
        let currentValue = parseFloat(valueElement.textContent);
        
        // 随机变化
        const change = (Math.random() - 0.5) * 0.05 * currentValue;
        const newValue = currentValue + change;
        
        // 更新值
        valueElement.textContent = newValue.toFixed(newValue < 0.1 ? 3 : 1);
        
        // 更新趋势
        const trendSpan = trendElement.querySelector('span');
        
        if (change > 0) {
            trendElement.className = 'stream-trend up';
            trendElement.innerHTML = '<i class="fas fa-arrow-up"></i><span>+' + Math.abs(change).toFixed(3) + '</span>';
        } else if (change < 0) {
            trendElement.className = 'stream-trend down';
            trendElement.innerHTML = '<i class="fas fa-arrow-down"></i><span>-' + Math.abs(change).toFixed(3) + '</span>';
        } else {
            trendElement.className = 'stream-trend steady';
            trendElement.innerHTML = '<i class="fas fa-minus"></i><span>0.000</span>';
        }
        
        // 随机更改状态 (较小概率)
        if (Math.random() < 0.2) {
            const statuses = ['normal', 'warning', 'error'];
            const statusTexts = ['正常', '偏高', '异常'];
            const randomIndex = Math.floor(Math.random() * 3);
            
            statusElement.className = 'stream-status ' + statuses[randomIndex];
            statusElement.textContent = statusTexts[randomIndex];
        }
    });
    
    // 更新预测结果
    updatePredictions();
}

// 更新预测结果
function updatePredictions() {
    const predictionItems = document.querySelectorAll('.prediction-item');
    
    predictionItems.forEach(item => {
        const valueElement = item.querySelector('.prediction-value');
        const confidenceBar = item.querySelector('.confidence-bar');
        const confidenceSpan = item.querySelector('.confidence span');
        
        // 获取当前值
        let currentText = valueElement.textContent;
        
        // 对不同类型的预测值进行不同处理
        if (currentText.includes('°C')) {
            // 温度
            let temp = parseFloat(currentText);
            const newTemp = temp + (Math.random() - 0.5) * 2;
            valueElement.textContent = newTemp.toFixed(1) + ' °C';
        } else if (currentText.includes('%')) {
            // 百分比
            let percent = parseFloat(currentText);
            const newPercent = percent + (Math.random() - 0.5) * 0.005;
            valueElement.textContent = newPercent.toFixed(3) + ' %';
        } else if (currentText.includes('分')) {
            // 时间
            let minutes = parseInt(currentText);
            let seconds = parseInt(currentText.split('分')[1]);
            
            seconds = seconds - Math.floor(Math.random() * 10);
            if (seconds < 0) {
                minutes--;
                seconds += 60;
            }
            
            valueElement.textContent = minutes + ' 分 ' + seconds + ' 秒';
        } else if (currentText.includes('m³/h')) {
            // 流量
            let flow = parseFloat(currentText);
            const newFlow = flow + (Math.random() - 0.5) * 5;
            valueElement.textContent = Math.round(newFlow) + ' m³/h';
        }
        
        // 随机更改置信度
        const confidence = parseInt(confidenceBar.style.width);
        const newConfidence = Math.max(50, Math.min(98, confidence + (Math.random() - 0.5) * 5));
        confidenceBar.style.width = newConfidence + '%';
        confidenceSpan.textContent = newConfidence + '% 置信度';
        
        // 根据置信度更新颜色
        const confidenceElement = item.querySelector('.confidence');
        if (newConfidence >= 90) {
            confidenceElement.className = 'confidence high';
        } else if (newConfidence >= 70) {
            confidenceElement.className = 'confidence medium';
        } else {
            confidenceElement.className = 'confidence low';
        }
    });
}

// 初始化下拉菜单
function initDropdowns() {
    const dropdownToggles = document.querySelectorAll('.dropdown-toggle');
    
    dropdownToggles.forEach(toggle => {
        toggle.addEventListener('click', function() {
            const dropdown = this.nextElementSibling;
            dropdown.classList.toggle('show');
            
            // 点击其他地方关闭下拉菜单
            document.addEventListener('click', function closeDropdown(e) {
                if (!e.target.matches('.dropdown-toggle') && !e.target.closest('.dropdown-menu')) {
                    dropdown.classList.remove('show');
                    document.removeEventListener('click', closeDropdown);
                }
            });
        });
    });
}

// 初始化参数选择器
function initParameterSelector() {
    const paramSelector = document.querySelector('.data-selector select');
    if (paramSelector) {
        paramSelector.addEventListener('change', function() {
            const placeholder = document.querySelector('.chart-placeholder p');
            if (placeholder) {
                placeholder.textContent = this.options[this.selectedIndex].text + '趋势图将在这里显示';
            }
        });
    }
}

// 初始化时间选择器
function initTimeSelector() {
    const timeButtons = document.querySelectorAll('.time-btn');
    
    timeButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            timeButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 初始化过滤器按钮
function initFilterButtons() {
    const filterButtons = document.querySelectorAll('.filter-btn');
    const anomalyItems = document.querySelectorAll('.anomaly-item');
    
    filterButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            filterButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            const filter = this.textContent.toLowerCase();
            
            anomalyItems.forEach(item => {
                if (filter === '全部') {
                    item.style.display = 'flex';
                } else if (filter === '警告' && item.classList.contains('warning')) {
                    item.style.display = 'flex';
                } else if (filter === '错误' && item.classList.contains('error')) {
                    item.style.display = 'flex';
                } else if (filter === '信息' && item.classList.contains('info')) {
                    item.style.display = 'flex';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    });
}

// 初始化图表（这里是一个占位符，实际项目中应该使用真实的图表库，如ECharts、Chart.js等）
function initCharts() {
    console.log('图表初始化功能将在实际开发中实现');
    // 在实际项目中，这里应该初始化实际的图表
    // 例如:
    /*
    const chartContainer = document.querySelector('.analysis-chart');
    const myChart = echarts.init(chartContainer);
    const option = {
        xAxis: { type: 'time' },
        yAxis: { type: 'value' },
        series: [{
            data: generateRandomData(),
            type: 'line'
        }]
    };
    myChart.setOption(option);
    */
}

// 模拟实时数据更新
function startRealTimeUpdates() {
    // 每10秒更新一次数据
    setInterval(updateStreamData, 10000);
}

// 处理异常项的按钮点击
document.addEventListener('click', function(e) {
    if (e.target.matches('.action-btn')) {
        const anomalyItem = e.target.closest('.anomaly-item');
        if (anomalyItem) {
            // 添加处理动画
            anomalyItem.classList.add('processing');
            
            // 如果点击的是"忽略"或"确认"按钮，则移除该项
            if (e.target.textContent === '忽略' || e.target.textContent === '确认') {
                setTimeout(() => {
                    anomalyItem.style.height = '0';
                    anomalyItem.style.opacity = '0';
                    anomalyItem.style.margin = '0';
                    anomalyItem.style.padding = '0';
                    setTimeout(() => {
                        anomalyItem.remove();
                    }, 300);
                }, 500);
            } else {
                // 其他按钮添加处理效果
                setTimeout(() => {
                    anomalyItem.classList.remove('processing');
                    
                    // 添加处理中标记
                    const meta = anomalyItem.querySelector('.anomaly-meta');
                    if (meta) {
                        const statusElement = document.createElement('span');
                        statusElement.className = 'anomaly-status';
                        statusElement.textContent = '处理中';
                        meta.appendChild(statusElement);
                    }
                    
                    // 禁用按钮
                    const buttons = anomalyItem.querySelectorAll('.action-btn');
                    buttons.forEach(btn => {
                        btn.disabled = true;
                        btn.classList.add('disabled');
                    });
                }, 800);
            }
        }
    }
}); 